import blue
import bluepy
import xtriui
import uix
import mathUtil
import uthread
import util
import state
import base
import menu
import trinity
import fleetbr
import uiutil
import uiconst
import pos
import uicls
import entities
SHOWLABELS_NEVER = 0
SHOWLABELS_ONMOUSEENTER = 1
SHOWLABELS_ALWAYS = 2

def AttachIcon(self, icon, track = None, where = 'top', menuFunc = None, hint = None):
    if util.GetAttrs(self, 'sr', 'hitchhiker'):
        self.sr.hitchhiker.Close()
        self.sr.hitchhiker = None
    if icon:
        if (track is None):
            track = self
        self.sr.hitchhiker = BracketHitchhiker(icon)
        self.sr.hitchhiker.Startup(self, track)
        self.sr.hitchhiker.hint = hint
        self.sr.hitchhiker.align = uix.UI_ALABSOLUTE
        self.sr.hitchhiker.pos = where
        if menuFunc:
            self.sr.hitchhiker.GetMenu = menuFunc


AttachIcon = uiutil.ParanoidDecoMethod(AttachIcon, ('sr'))

class SlimDeco(bluepy.WrapBlueClass('triui.UISprite')):
    __guid__ = 'xtriui.SlimDeco'
    __persistvars__ = ('sr',)
    __nonpersistvars__ = ('wr',)
    uthreadedEvents = (uix.UI_CLICK,
     uix.UI_CHAR,
     uix.UI_ENDDRAG,
     uix.UI_KEYUP,
     uix.UI_KEYDOWN)

    def __init__(self):
        self.sr = uiutil.Bunch()
        self.wr = util.WeakRefAttrObject()
        self.init()



    def init(self):
        return 



    def ProcessTriuiMessage(self, what_happened, *args):
        if ((what_happened != uix.UI_CLOSE) and (self.destroyed or eve.triapp.uilib.desktop.destroyed)):
            return 
        Handler = getattr(self, self.eventMap[what_happened], None)
        customArgs = ()
        if (type(Handler) == type(())):
            customArgs = Handler[1:]
            Handler = Handler[0]
        if (Handler and (what_happened in self.uthreadedEvents)):
            tmp = Handler
            Handler = lambda *args, **kw: uthread.new(tmp, *args, **kw)
        try:
            if Handler:
                Handler(*((customArgs + (self)) + args))

        finally:
            if (what_happened == uix.UI_CLOSE):
                self.TearEvents()
                self.sr = None
                self.wr = None



    SendMessage = ProcessTriuiMessage

    def TearEvents(self):
        [ self.UnloadEvent(funcName) for funcName in self.events ]



    def LoadEvents(self, events):
        if (('GetMenu' in events) and ('MouseUp' not in events)):
            events += ['MouseUp']
        if ('Close' not in events):
            events += ['Close']
        self.events = events
        self.eventMap = {}
        [ self.LoadEvent(funcName) for funcName in events ]



    def UnloadEvent(self, funcName):
        setattr(self, ('Do%s' % funcName), None)



    def LoadEvent(self, funcName):
        eventConst = getattr(uix, ('UI_%s' % funcName.upper()), None)
        if eventConst:
            setattr(self, ('Do%s' % funcName), lambda *args, **kw: self.SendMessage(eventConst, *args, **kw))
            self.eventMap[eventConst] = ('On%s' % funcName)



    def OnMouseUp(self, btn, btnflag, *args):
        if ((eve.triapp.uilib.mouseTravel > 32) or ((btnflag != 1) or eve.triapp.uilib.rightbtn)):
            return 
        m = self.GetMenu()
        if ((not m) or ((not filter(None, m)) or getattr(self, 'showingMenu', 0))):
            return 
        self.showingMenu = 1
        mv = self._SlimDeco__displaying = menu.CreateMenuView(menu.CreateMenuFromList(m), None, getattr(self, 'minwidth', None))
        (x, y,) = (min((eve.triapp.uilib.desktop.width - mv.width), (eve.triapp.uilib.x + 10)), min((eve.triapp.uilib.desktop.height - mv.height), eve.triapp.uilib.y))
        (mv.left, mv.top,) = (x, y)
        uicore.layer.menu.children.insert(0, mv)
        self.showingMenu = 0



    def GetMenu(self):
        return []




class BracketChild(SlimDeco):
    __guid__ = 'xtriui.BracketChild'

    def init(self):
        self.LoadEvents(['MouseUp',
         'MouseMove',
         'MouseExit',
         'MouseEnter',
         'Click',
         'Close',
         'MouseHover',
         'MouseDown'])
        self.sr.clicktime = None



    def Startup(self, bracket):
        self.wr.bracket = bracket



    def GetMenu(self):
        bracket = self.wr.bracket
        if bracket:
            return bracket.GetMenu()



    def OnMouseUp(self, btn, btnflag, *args):
        self.sr.expandTimer = None
        if ((eve.triapp.uilib.mouseTravel > 32) or ((btnflag != 1) or eve.triapp.uilib.rightbtn)):
            return 
        uthread.new(self.MouseUp, btn, btnflag)



    def MouseUp(self, btn, btnflag, *args):
        m = self.GetMenu()
        if ((not m) or ((not filter(None, m)) or getattr(self, 'showingMenu', 0))):
            return 
        self.showingMenu = 1
        mv = self._BracketChild__displaying = menu.CreateMenuView(menu.CreateMenuFromList(m), None, getattr(self, 'minwidth', None))
        (x, y,) = (min((eve.triapp.uilib.desktop.width - mv.width), (eve.triapp.uilib.x + 10)), min((eve.triapp.uilib.desktop.height - mv.height), eve.triapp.uilib.y))
        (mv.left, mv.top,) = (x, y)
        uicore.layer.menu.children.insert(0, mv)
        self.showingMenu = 0
        self.downpos = None



    def GetMouseTravel(self):
        if self.downpos:
            (x, y,) = (eve.triapp.uilib.x, eve.triapp.uilib.y)
            v = trinity.TriVector(float((x - self.downpos[0])), float((y - self.downpos[1])), 0.0)
            return int(v.Length())



    def OnMouseDown(self, *args):
        bracket = self.wr.bracket
        if ((bracket and getattr(bracket.wr, 'slimItem', None)) and sm.GetService('menu').TryExpandActionMenu(bracket.itemID, eve.triapp.uilib.x, eve.triapp.uilib.y, self)):
            return 
        nav = uix.GetInflightNav(0)
        if nav:
            nav.looking = 1



    def OnMouseEnter(self, *args):
        uix.LogInfo('Bracket OnMouseEnter')
        if eve.triapp.uilib.leftbtn:
            return 
        bracket = self.wr.bracket
        if bracket:
            if ((not getattr(bracket, 'invisible', False)) or bracket.sr.tempIcon):
                if (bracket.itemID == sm.GetService('bracket').CheckingOverlaps()):
                    return 
                sm.GetService('state').SetState(bracket.itemID, state.mouseOver, 1)



    def OnMouseMove(self, *args):
        if eve.triapp.uilib.leftbtn:
            return 
        bracket = self.wr.bracket



    def OnMouseHover(self, *args):
        if eve.triapp.uilib.leftbtn:
            return 
        bracket = self.wr.bracket
        if (bracket and (bracket.trackBall or bracket.trackTransform)):
            if (bracket.itemID == sm.GetService('bracket').CheckingOverlaps()):
                return 
            sm.GetService('bracket').CheckOverlaps(bracket, (not getattr(bracket, 'inflight', 1)))



    def OnMouseExit(self, *args):
        uix.LogInfo('Bracket OnMouseExit')
        if eve.triapp.uilib.leftbtn:
            return 
        bracket = self.wr.bracket
        if bracket:
            if ((getattr(bracket, 'trackBall', 'blah') is None) and (getattr(bracket, 'trackTransform', 'blah') is None)):
                return 
            over = eve.triapp.uilib.mouseOver
            if (getattr(over, '__guid__', '').startswith('xtriui.BracketChild') and (over.wr.bracket and (over.wr.bracket == self.wr.bracket))):
                return 
            if (bracket.itemID == sm.GetService('bracket').CheckingOverlaps()):
                return 
            sm.GetService('state').SetState(bracket.itemID, state.mouseOver, 0)



    def OnClick(self, *args):
        if ((not self) or (getattr(self, 'sr', None) is None)):
            return 
        self.sr.expandTimer = None
        bracket = self.wr.bracket
        if not bracket:
            return 
        if (self.sr.clicktime and (blue.os.TimeDiffInMs(self.sr.clicktime) < 1000.0)):
            cameraSvc = sm.StartService('camera')
            if cameraSvc.IsFreeLook():
                cameraSvc.LookAt(bracket.itemID)
                return 
            sm.GetService('state').SetState(bracket.itemID, state.selected, 1)
            slimItem = getattr(bracket.wr, 'slimItem', None)
            if slimItem:
                sm.GetService('menu').Activate(slimItem)
            if ((not self) or (getattr(self, 'sr', None) is None)):
                return 
            self.sr.clicktime = None
        else:
            sm.GetService('state').SetState(bracket.itemID, state.selected, 1)
            if sm.GetService('target').IsTarget(bracket.itemID):
                sm.GetService('state').SetState(bracket.itemID, state.activeTarget, 1)
            if ((not self) or (getattr(self, 'sr', None) is None)):
                return 
            self.sr.clicktime = blue.os.GetTime()
        sm.GetService('menu').TacticalItemClicked(bracket.itemID)




class BracketHitchhiker(BracketChild):
    __guid__ = 'xtriui.BracketHitchhiker'

    def Startup(self, bracket, track):
        self.updatingLabel = 0
        self.wr.bracket = bracket
        self.wr.track = track
        self.UpdateHitchhikerPos()
        self.sr.updatePosTimer = base.AutoTimer(5, self.UpdateHitchhikerPos)



    def UpdateHitchhikerPos(self):
        if (util.GetAttrs(self, 'wr', 'track') is None):
            if (self is not None):
                self.Close()
            return 
        (l, t, w, h,) = self.wr.track.GetAbsolute()
        t = max(0, t)
        cx = (l + (w / 2))
        cy = (t + (h / 2))
        pos = getattr(self, 'pos', 'top')
        if (pos == 'top'):
            self.left = (cx - (self.width / 2))
            self.top = ((cy - 8) - self.height)
        elif (pos == 'center'):
            self.left = (cx - (self.width / 2))
            self.top = (cy - (self.height / 2))




class BracketLabel(BracketChild):
    __guid__ = 'xtriui.BracketLabel'

    def Startup(self, bracket):
        self.updatingLabel = 0
        self.sr.label = uicls.Label(text='', parent=self, left=6, top=3, name='label', letterspace=1, fontsize=9, state=uiconst.UI_DISABLED, uppercase=1)
        self.wr.bracket = bracket
        self.UpdateLabel()
        self.sr.updateTimer = base.AutoTimer(500, self.UpdateLabel)
        self.UpdatePos()
        self.sr.updatePosTimer = base.AutoTimer(5, self.UpdatePos)



    def UpdatePos(self):
        if ((self is None) or self.destroyed):
            return 
        bracket = self.wr.bracket
        if ((bracket is None) or bracket.destroyed):
            self.Close()
            return 
        (l, t, w, h,) = bracket.GetAbsolute()
        cx = (l + (w / 2))
        cy = (t + (h / 2))
        if ((((cx + 8) + 2) + self.width) > bracket.parent.absoluteRight):
            self.left = int((((cx - 8) - 2) - self.width))
        else:
            self.left = int(((cx + 8) + 2))
        (bl, bt, bw, bh,) = bracket.GetAbsolute()
        self.top = int(((cy - (self.sr.label.textheight / 2)) - 2))



    def UpdateLabel(self):
        if (self.updatingLabel or ((self is None) or (self.destroyed or (not self.wr.bracket)))):
            return 
        self.updatingLabel = 1
        bracket = self.wr.bracket
        newStr = bracket.displayName
        if getattr(bracket, 'showDistance', 1):
            distance = bracket.GetDistance()
            if distance:
                newStr += (' ' + util.FmtDist(distance))
        if (newStr != self.sr.label.text):
            self.sr.label.text = newStr
            self.width = (self.sr.label.textwidth + 12)
        self.updatingLabel = 0




class UpdateEntry(object):
    __guid__ = 'xtriui.UpdateEntry'
    broadcastIconSize = ('smallIcon', 16)

    def Startup_update(self, *args):
        self.hostilePath = 'res:/UI/Inflight/overview_hostile.blue'
        self.activetargetPath = 'res:/UI/Inflight/overview_activetarget.blue'
        self.targetedPath = 'res:/UI/Inflight/overview_targeted.blue'
        self.targetingPath = None
        self.stateItemID = None
        self.sr.targetItem = None
        self.sr.hitchhiker = None
        self.sr.fleetBroadcastIcon = None



    def Load_update(self, slimItem, *args):
        if (slimItem is None):
            return 
        self.stateItemID = slimItem.itemID
        (selected, hilited, attacking, hostile, targeting, targeted,) = sm.GetService('state').GetStates(self.stateItemID, [state.selected,
         state.mouseOver,
         state.threatAttackingMe,
         state.threatTargetsMe,
         state.targeting,
         state.targeted])
        self.Select(selected)
        self.Hilite(hilited)
        self.Targeted(targeted)
        activeTargetID = sm.GetService('target').GetActiveTargetID()
        isActive = (activeTargetID and (activeTargetID == slimItem.itemID))
        self.ActiveTarget(isActive)
        if not isActive:
            self.Targeting(targeting)
            if not targeting:
                (targeted,) = sm.GetService('state').GetStates(slimItem.itemID, [state.targeted])
                self.Targeted(targeted)
        if self.updateItem:
            uthread.pool('UpdateEntry::Load_update --> UpdateStates', self.UpdateStates, slimItem)
            self.Attacking(attacking)
            self.Hostile(((not attacking) and hostile), attacking)
        else:
            f = self.sr.Get('flag', None)
            self.sr.flag = None
            if f:
                f.Close()
            f = self.sr.Get('bgColor', None)
            self.sr.bgColor = None
            if f:
                f.Close()
            if (self.sr.Get('hostile_attacking', None) is not None):
                ha = self.sr.hostile_attacking
                self.sr.hostile_attacking = None
                ha.Close()
            if self.sr.icon:
                self.SetColor(1.0, 1.0, 1.0)
                if ((slimItem.groupID == const.groupStargate) and slimItem.jumps):
                    destinationPath = sm.GetService('starmap').GetDestinationPath()
                    if (slimItem.jumps[0].locationID in destinationPath):
                        self.SetColor(1.0, 1.0, 0.0)
                    if getattr(self, 'IsBracket', 0):
                        uiutil.SetOrder(self, 0)
                if IsForbiddenContainer(slimItem):
                    self.SetColor(1.0, 1.0, 0.0)
                else:
                    if IsAbandonedContainer(slimItem):
                        self.SetColor(0.2, 0.5, 1.0)
        uthread.worker('bracket.UpdateViewed', self.UpdateViewed, slimItem)
        uthread.worker('bracket.UpdateWreckEmpty', self.UpdateWreckEmpty, slimItem)
        uthread.worker('bracket.UpdateFleetBroadcasts', self.UpdateFleetBroadcasts, slimItem)



    def UpdateViewed(self, slimItem):
        if self.destroyed:
            return 
        if ((slimItem.groupID == const.groupWreck) and sm.GetService('wreck').IsViewedWreck(slimItem.itemID)):
            self.Viewed(True)



    def UpdateWreckEmpty(self, slimItem):
        if self.destroyed:
            return 
        if (slimItem and (slimItem.groupID == const.groupWreck)):
            self.WreckEmpty(slimItem.isEmpty)



    def UpdateFleetBroadcasts(self, slimItem):
        (broadcastID, broadcastType, broadcastData,) = sm.GetService('fleet').GetCurrentFleetBroadcastOnItem(slimItem.itemID)
        if (broadcastID is None):
            return 
        if ((self is None) or self.destroyed):
            return 
        for typeName in fleetbr.types:
            if (broadcastType == getattr(state, ('gb%s' % typeName))):
                handler = getattr(self, ('GB%s' % typeName), None)
                if (handler is None):
                    self.FleetBroadcast(True, typeName, broadcastID, *broadcastData)
                else:
                    handler(True, broadcastID, *broadcastData)
                break




    def UpdateStates(self, slimItem):
        sm.GetService('tactical').UpdateStates(slimItem, self)



    def OnStateChange(self, itemID, flag, true, *args):
        if ((flag == state.lookingAt) and hasattr(self, 'ShowTempIcon')):
            if self.stateItemID == eve.session.shipid == itemID:
                if not true:
                    self.ShowTempIcon()
                else:
                    self.HideTempIcon()
        if (self.stateItemID != itemID):
            return 
        if (flag == state.mouseOver):
            self.Hilite(true)
        elif (flag == state.selected):
            self.Select(true)
        elif (flag == state.threatTargetsMe):
            attacking = sm.StartService('state').GetStates(itemID, [state.threatAttackingMe])
            if ((attacking is not None) and (len(attacking) > 0)):
                attacking = attacking[0]
            else:
                attacking = 0
            self.Hostile(true, attacking=attacking)
        elif (flag == state.threatAttackingMe):
            self.Attacking(true)
        elif (flag == state.targeted):
            self.Targeted(true)
        elif (flag == state.targeting):
            self.Targeting(true)
        elif (flag == state.activeTarget):
            self.ActiveTarget(true)
        elif (flag == state.flagWreckAlreadyOpened):
            self.Viewed(true)
        elif (flag == state.flagWreckEmpty):
            self.WreckEmpty(true)
        else:
            for name in fleetbr.types:
                if (flag == getattr(state, ('gb%s' % name))):
                    handler = getattr(self, ('GB%s' % name), None)
                    if (handler is None):
                        self.FleetBroadcast(true, name, *args)
                    else:
                        handler(true, *args)
                    break




    def SetColor(self, r, g, b, _save = True):
        if _save:
            self._originalIconColor = (r,
             g,
             b)
        self.sr.icon.color.SetRGB(r, g, b)
        if (util.GetAttrs(self, 'sr', 'tempIcon') is not None):
            self.sr.tempIcon.color.SetRGB(r, g, b)



    def Viewed(self, true):
        if not hasattr(self, '_originalIconColor'):
            color = self.sr.icon.color
            self._originalIconColor = (color.r,
             color.g,
             color.b)
        (r, g, b,) = self._originalIconColor
        if true:
            attenuation = 0.55
            self.SetColor((r * attenuation), (g * attenuation), (b * attenuation), _save=False)
        else:
            self.SetColor(r, g, b, _save=False)



    def WreckEmpty(self, true):
        if true:
            wreckIcon = '38_29'
            uix.MapSprite(wreckIcon, self.sr.icon)
            if (util.GetAttrs(self, 'sr', 'tempIcon') and (self.sr.tempIcon is not None)):
                uix.MapSprite(wreckIcon, self.sr.tempIcon)
            (self.iconX, self.iconY,) = uix.GetTextureTranslation(wreckIcon, 16)
        else:
            wreckIcon = '38_28'
            uix.MapSprite(wreckIcon, self.sr.icon)
            if (util.GetAttrs(self, 'sr', 'tempIcon') and (self.sr.tempIcon is not None)):
                uix.MapSprite(wreckIcon, self.sr.tempIcon)
            (self.iconX, self.iconY,) = uix.GetTextureTranslation(wreckIcon, 16)



    def GBTarget(self, active, fleetBroadcastID, charID, targetNo = None):
        self.FleetBroadcast(active, 'Target', fleetBroadcastID, charID)
        if (util.GetAttrs(self, 'sr', 'targetNo') is not None):
            self.sr.targetNo.Close()
            self.sr.targetNo = None
        if active:
            self.sr.targetNo = uicls.Label(text=targetNo, parent=self, idx=0, left=15, top=-6, fontsize=14, state=uiconst.UI_DISABLED)



    def FleetBroadcast(self, active, broadcastType, fleetBroadcastID, charID):
        if active:
            self.fleetBroadcastSender = charID
            self.fleetBroadcastType = broadcastType
            self.fleetBroadcastID = fleetBroadcastID
            if (self.sr.Get('fleetBroadcastIcon') and (self.sr.fleetBroadcastIcon is not None)):
                self.sr.fleetBroadcastIcon.Close()
                self.sr.fleetBroadcastIcon = None
            (sizeName, pixels,) = self.broadcastIconSize
            icon = fleetbr.types[broadcastType][sizeName]
            if not self.sr.icon:
                self.LoadIcon(self.iconX, self.iconY)
            iconLeft = (((self.sr.icon.width / 2) + self.sr.icon.left) - (pixels / 2))
            iconTop = (((self.sr.icon.height / 2) + self.sr.icon.top) - (pixels / 2))
            self.sr.fleetBroadcastIcon = uicls.Icon(icon=icon, parent=self, align=uiconst.RELATIVE, pos=(iconLeft,
             iconTop,
             16,
             16), state=uiconst.UI_DISABLED)
            self.sr.fleetBroadcastIcon.name = 'fleetBroadcastIcon'
            self.sr.fleetBroadcastIcon.state = uix.UI_DISABLED
        elif (fleetBroadcastID == getattr(self, 'fleetBroadcastID', None)):
            if (self.sr.Get('fleetBroadcastIcon') and (self.sr.fleetBroadcastIcon is not None)):
                self.sr.fleetBroadcastIcon.Close()
                self.sr.fleetBroadcastIcon = None
            self.fleetBroadcastSender = self.fleetBroadcastType = self.fleetBroadcastID = None



    def ActiveTarget(self, activestate):
        if not self.activetargetPath:
            return 
        for each in self.children[:]:
            if (each.name == 'activetarget'):
                each.Close()

        if activestate:
            if self.activetargetPath:
                activeTarget = blue.os.LoadObject(self.activetargetPath)
                self.children.append(activeTarget)
                rot = uiutil.FindChild(activeTarget, 'rotate')
                if rot:
                    sm.GetService('ui').Rotate(rot, 2.0)
                    sm.GetService('ui').BlinkSpriteA(rot.children[0], 1.0, 500.0, 0)
        else:
            (targeted,) = sm.GetService('state').GetStates(self.stateItemID, [state.targeted])
            self.Targeted(targeted, 0)



    def Targeted(self, state, tryActivate = 1):
        obs = sm.GetService('target').IsObserving()
        if ((not self.targetedPath) or obs):
            return 
        if state:
            if not self.sr.targetItem:
                targ = blue.os.LoadObject(self.targetedPath)
                lines = uiutil.FindChild(targ, 'lines')
                if not settings.user.ui.Get('targetCrosshair', 1):
                    lines.state = uix.UI_HIDDEN
                else:
                    lines.state = uix.UI_DISABLED
                    _FixLines(targ)
                self.children.append(targ)
                self.sr.targetItem = targ
            sq = uiutil.FindChild(self.sr.targetItem, 'square')
            if ((sq is not None) and (not sq.destroyed)):
                sq.state = uix.UI_DISABLED
        elif tryActivate:
            self.ActiveTarget(0)
        t = self.sr.targetItem
        self.sr.targetItem = None
        if (t is not None):
            t.Close()



    def Targeting(self, state):
        if state:
            if not self.targetedPath:
                return 
            if ((self.sr.targetItem is None) or self.sr.targetItem.destroyed):
                self.Targeted(1)
            if self.sr.targetItem:
                uthread.new(self.CountDown, self.sr.targetItem)
                targeting = uiutil.FindChild(self.sr.targetItem, 'targeting')
                targeting.state = uix.UI_DISABLED
                uthread.new(self.AnimateTargeting, targeting)
        elif self.sr.targetItem:
            uiutil.FindChild(self.sr.targetItem, 'targeting').state = uix.UI_HIDDEN



    def AnimateTargeting(self, item):
        while ((not item.destroyed) and (item.state != uix.UI_HIDDEN)):
            (start, ndt,) = (blue.os.GetTime(1), 0.0)
            while (ndt != 1.0):
                ndt = max(ndt, min((blue.os.TimeDiffInMs(start) / 333.0), 1.0))
                item.left = item.top = item.width = item.height = int(mathUtil.Lerp(-12, 10, ndt))
                blue.pyos.synchro.Yield()





    def CountDown(self, *args):
        return 



    def Hilite(self, state):
        if self.sr.hilite:
            self.sr.hilite.state = [uix.UI_HIDDEN, uix.UI_DISABLED][state]



    def Select(self, state):
        if self.sr.selection:
            if state:
                self.sr.node.scroll.DeselectAll(report=False)
                self.sr.node.selected = True
            else:
                self.sr.node.selected = False
            self.sr.selection.state = [uix.UI_HIDDEN, uix.UI_DISABLED][state]



    def Hostile(self, state, attacking = 0):
        isBracket = getattr(self, 'IsBracket', 0)
        if ((not isBracket) and ((self.sr.icon is None) or (self.sr.icon.state == uix.UI_HIDDEN))):
            state = 0
        if state:
            if not self.sr.hostile_attacking:
                self.sr.hostile_attacking = blue.os.LoadObject(self.hostilePath)
                self.sr.hostile_attacking.color.SetRGB(1.0, 1.0, 1.0, 0.0)
                self.children.insert(0, self.sr.hostile_attacking)
                sm.GetService('ui').BlinkSpriteA(self.sr.hostile_attacking, 0.75, 500, None, passColor=0)
            self.sr.hostile_attacking.state = uix.UI_DISABLED
            if not attacking:
                self.sr.hostile_attacking.rectLeft = 0
            else:
                self.sr.hostile_attacking.rectLeft = [18, 32][isBracket]
            if not isBracket:
                self.sr.hostile_attacking.left = self.sr.icon.left
        elif ((not attacking) and self.sr.hostile_attacking):
            h = self.sr.hostile_attacking
            self.sr.hostile_attacking = None
            h.Close()



    def Attacking(self, state):
        isBracket = getattr(self, 'IsBracket', 0)
        if ((not isBracket) and ((self.sr.icon is None) or (self.sr.icon.state == uix.UI_HIDDEN))):
            state = 0
        if state:
            if not self.sr.hostile_attacking:
                self.sr.hostile_attacking = blue.os.LoadObject(self.hostilePath)
                self.sr.hostile_attacking.color.SetRGB(1.0, 1.0, 1.0, 0.0)
                self.children.insert(0, self.sr.hostile_attacking)
                sm.GetService('ui').BlinkSpriteA(self.sr.hostile_attacking, 0.75, 500, None, passColor=0)
            self.sr.hostile_attacking.state = uix.UI_DISABLED
            self.sr.hostile_attacking.rectLeft = [18, 32][isBracket]
            if not isBracket:
                self.sr.hostile_attacking.left = self.sr.icon.left
        elif (self.itemID in sm.GetService('target').GetTargetedBy()):
            self.Hostile(1)
        elif self.sr.hostile_attacking:
            h = self.sr.hostile_attacking
            self.sr.hostile_attacking = None
            h.Close()



    def UpdateStructureState(self, slimItem):
        if not util.IsStructure(slimItem.categoryID):
            return 
        self.lastPosEvent = blue.os.GetTime()
        (stateName, stateTimestamp, stateDelay,) = sm.GetService('pwn').GetStructureState(slimItem)
        if (self.sr.posStatus is None):
            self.sr.posStatus = uicls.Label(text=getattr(mls, ('UI_GENERIC_' + stateName.upper())), parent=self, left=24, top=32, fontsize=9, letterspace=1, uppercase=1, linespace=14, state=uiconst.UI_NORMAL)
        else:
            uix.Flush(self.sr.posStatus)
            self.sr.posStatus.text = getattr(mls, ('UI_GENERIC_' + stateName.upper()))
        if (stateName in ('anchoring', 'onlining', 'unanchoring', 'reinforced', 'operating', 'incapacitated')):
            uthread.new(self.StructureProgress, self.lastPosEvent, stateName, stateTimestamp, stateDelay)



    def UpdateOrbitalState(self, slimItem):
        if not util.IsOrbital(slimItem.categoryID):
            return 
        self.lastOrbitalEvent = blue.os.GetTime()
        statusString = entities.GetEntityStateString(slimItem.orbitalState)
        if (self.sr.orbitalStatus is None):
            self.sr.orbitalStatus = uicls.Label(text=statusString, parent=self, left=24, top=32, fontsize=9, letterspace=1, uppercase=1, linespace=14, state=uiconst.UI_NORMAL)
        else:
            uix.Flush(self.sr.orbitalStatus)
            self.sr.orbitalStatus.text = statusString
        if (slimItem.orbitalState in (entities.STATE_ONLINING,
         entities.STATE_OFFLINING,
         entities.STATE_ANCHORING,
         entities.STATE_UNANCHORING)):
            uthread.new(self.OrbitalProgress, self.lastOrbitalEvent, slimItem)



    def UpdateOutpostState(self, slimItem, oldSlimItem = None):
        if ((slimItem.groupID == const.groupStation) and (hasattr(slimItem, 'structureState') and (slimItem.structureState in [pos.STRUCTURE_SHIELD_REINFORCE, pos.STRUCTURE_ARMOR_REINFORCE]))):
            endTime = (slimItem.startTimestamp + (slimItem.delayTime * const.MSEC))
            if (getattr(self, 'reinforcedProgressThreadRunning', False) == False):
                uthread.new(self.ReinforcedProgress, slimItem.startTimestamp, endTime)
        elif ((slimItem.groupID == const.groupStation) and (hasattr(slimItem, 'structureState') and (slimItem.structureState == pos.STRUCTURE_INVULNERABLE))):
            if not hasattr(self, 'reinforcedTimeText'):
                self.reinforcedTimeText = uicls.Label(text=' ', parent=self, left=-10, top=32, fontsize=9, letterspace=1, uppercase=1, linespace=14, state=uiconst.UI_NORMAL)
            timeText = self.reinforcedTimeText
            timeText.text = mls.UI_GENERIC_INVULNERABLE
            timeText.left = -32
            self.ChangeReinforcedState(uiconst.UI_NORMAL)
        elif ((oldSlimItem is not None) and ((getattr(oldSlimItem, 'structureState', None) in [pos.STRUCTURE_SHIELD_REINFORCE, pos.STRUCTURE_ARMOR_REINFORCE]) and (getattr(slimItem, 'structureState', None) not in [pos.STRUCTURE_SHIELD_REINFORCE, pos.STRUCTURE_ARMOR_REINFORCE]))):
            self.reinforcedProgressThreadRunning = False
        self.ChangeReinforcedState(uiconst.UI_HIDDEN)
        self.ChangeReinforcedState(uiconst.UI_HIDDEN)



    def UpdatePlanetaryLaunchContainer(self, slimItem):
        uthread.new(self._UpdatePlanetaryLaunchContainer, slimItem)



    def _UpdatePlanetaryLaunchContainer(self, slimItem):
        if (slimItem.typeID != const.typePlanetaryLaunchContainer):
            return 
        cnt = 0
        while ((slimItem.launchTime is None) and (cnt < 90)):
            blue.pyos.synchro.Sleep(1000)
            cnt += 1

        if ((getattr(self, 'planetaryLaunchContainerThreadRunning', False) == False) and (slimItem.launchTime is not None)):
            uthread.new(self.PlanetaryLaunchContainerProgress, slimItem.launchTime, long((slimItem.launchTime + const.piLaunchOrbitDecayTime)))



    def PlanetaryLaunchContainerProgress(self, startTime, endTime):
        self.planetaryLaunchContainerThreadRunning = True
        try:
            boxwidth = 82
            fillwidth = (boxwidth - 2)
            boxheight = 14
            fillheight = (boxheight - 2)
            boxtop = 30
            filltop = (boxtop + 1)
            boxleft = (-(boxwidth / 2) + 5)
            fillleft = (boxleft + 1)
            boxcolor = (1.0, 1.0, 1.0, 0.35)
            fillcolor = (1.0, 1.0, 1.0, 0.25)
            if not hasattr(self, 'reinforcedState'):
                self.burnupFill = uicls.Fill(parent=self, align=uiconst.TOPLEFT, width=fillwidth, height=fillheight, left=fillleft, top=filltop, color=fillcolor)
            burnupFill = self.burnupFill
            if not hasattr(self, 'burnupTimeText'):
                self.burnupTimeText = uicls.Label(text=' ', parent=self, left=-10, top=32, fontsize=9, letterspace=1, uppercase=1, linespace=14, state=uiconst.UI_NORMAL)
            timeText = self.burnupTimeText
            if not hasattr(self, 'burnupFrame'):
                self.burnupFrame = uicls.Frame(parent=self, align=uiconst.TOPLEFT, width=boxwidth, height=boxheight, left=boxleft, top=boxtop, color=boxcolor)
            frame = self.burnupFrame
            while ((not self.destroyed) and self.planetaryLaunchContainerThreadRunning):
                currentTime = blue.os.GetTime()
                portion = (float((currentTime - startTime)) / (endTime - startTime))
                if (portion > 1.0):
                    break
                width = min(int((portion * fillwidth)), fillwidth)
                width = (fillwidth - abs(width))
                if (burnupFill.width != width):
                    burnupFill.width = width
                newTimeText = util.FmtDate((endTime - currentTime), 'ss')
                if (timeText.text != newTimeText):
                    textWidth = uix.GetTextWidth(newTimeText, fontsize=9, hspace=1, uppercase=1)
                    timeText.text = newTimeText
                    timeText.left = -32
                blue.pyos.synchro.Sleep(1000)


        finally:
            self.planetaryLaunchContainerThreadRunning = False




    def ChangeReinforcedState(self, state):
        if hasattr(self, 'reinforcedState'):
            self.reinforcedState.state = state
        if hasattr(self, 'reinforcedTimeText'):
            self.reinforcedTimeText.state = state
        if hasattr(self, 'reinforcedFrame'):
            self.reinforcedFrame.state = state



    def ReinforcedProgress(self, startTime, endTime):
        self.reinforcedProgressThreadRunning = True
        try:
            boxwidth = 82
            fillwidth = (boxwidth - 2)
            boxheight = 14
            fillheight = (boxheight - 2)
            boxtop = 30
            filltop = (boxtop + 1)
            boxleft = (-(boxwidth / 2) + 5)
            fillleft = (boxleft + 1)
            boxcolor = (1.0, 1.0, 1.0, 0.35)
            fillcolor = (1.0, 1.0, 1.0, 0.25)
            if not hasattr(self, 'reinforcedState'):
                self.reinforcedState = uicls.Fill(parent=self, align=uiconst.TOPLEFT, width=fillwidth, height=fillheight, left=fillleft, top=filltop, color=fillcolor)
            p = self.reinforcedState
            if not hasattr(self, 'reinforcedTimeText'):
                self.reinforcedTimeText = uicls.Label(text=' ', parent=self, left=-10, top=32, fontsize=9, letterspace=1, uppercase=1, linespace=14, state=uiconst.UI_NORMAL)
            timeText = self.reinforcedTimeText
            if not hasattr(self, 'reinforcedFrame'):
                self.reinforcedFrame = uicls.Frame(parent=self, align=uiconst.TOPLEFT, width=boxwidth, height=boxheight, left=boxleft, top=boxtop, color=boxcolor)
            frame = self.reinforcedFrame
            self.ChangeReinforcedState(uiconst.UI_NORMAL)
            while ((not self.destroyed) and self.reinforcedProgressThreadRunning):
                currentTime = blue.os.GetTime()
                portion = (float((currentTime - startTime)) / (endTime - startTime))
                if (portion > 1.0):
                    break
                width = min(int((portion * fillwidth)), fillwidth)
                width = (fillwidth - abs(width))
                if (p.width != width):
                    p.width = width
                newTimeText = util.FmtDate((endTime - currentTime), 'ss')
                if (timeText.text != newTimeText):
                    textWidth = uix.GetTextWidth(newTimeText, fontsize=9, hspace=1, uppercase=1)
                    timeText.text = ((mls.UI_GENERIC_REINFORCED + '... <br>') + newTimeText)
                    timeText.left = -32
                blue.pyos.synchro.Sleep(250)


        finally:
            self.reinforcedProgressThreadRunning = False




    def UpdateCaptureProgress(self, captureData):
        slimItem = self.wr.slimItem
        if (slimItem.groupID != const.groupCapturePointTower):
            return 
        if captureData:
            self.captureData = captureData
        else:
            self.captureData = sm.GetService('bracket').GetCaptureData(self.itemID)
        if not self.captureData:
            return 
        if not getattr(self, 'captureTaskletRunning', False):
            uthread.new(self.CaptureProgress)



    def CaptureProgress(self):
        self.captureTaskletRunning = True
        boxwidth = 82
        fillwidth = (boxwidth - 2)
        boxheight = 14
        fillheight = (boxheight - 2)
        boxtop = 30
        filltop = (boxtop + 1)
        boxleft = (-(boxwidth / 2) + 5)
        fillleft = (boxleft + 1)
        boxcolor = (1.0, 1.0, 1.0, 0.35)
        fillcolor = (1.0, 1.0, 1.0, 0.25)
        frame = uicls.Frame(parent=self, align=uiconst.TOPLEFT, width=boxwidth, height=boxheight, left=boxleft, top=boxtop, color=boxcolor)
        if not hasattr(self, 'captureState'):
            self.captureState = uicls.Fill(parent=self, align=uiconst.TOPLEFT, width=0, height=fillheight, left=fillleft, top=filltop, color=fillcolor)
        p = self.captureState
        texttop = ((boxtop + boxheight) + 2)
        if not hasattr(self, 'captureStateText'):
            self.captureStateText = uicls.Label(text=' ', parent=self, left=boxleft, top=texttop, fontsize=9, letterspace=1, uppercase=1, state=uiconst.UI_NORMAL)
        t = self.captureStateText
        if not hasattr(self, 'captureStateTimeText'):
            self.captureStateTimeText = uicls.Label(text=' ', parent=self, left=-10, top=(filltop + 1), fontsize=9, letterspace=1, uppercase=1, state=uiconst.UI_NORMAL)
        timeText = self.captureStateTimeText
        portion = 0.0
        captureID = self.captureData.get('captureID', None)
        while ((not self.destroyed) and (portion < 1.0)):
            if (self.captureData['captureID'] != 'contested'):
                totalTimeMs = ((self.captureData['captureTime'] * 60) * 1000)
                timeDiff = blue.os.TimeDiffInMs(self.captureData['lastIncident'])
                portion = (float(timeDiff) / totalTimeMs)
                portion = (portion + (float(self.captureData['points']) / 100))
                width = min(int((portion * fillwidth)), fillwidth)
                width = abs(width)
                if (p.width != width):
                    p.width = width
                if (t.text != ((cfg.eveowners.Get(self.captureData['captureID']).name + ' ') + mls.UI_INFLIGHT_CAPTURING)):
                    t.text = ((cfg.eveowners.Get(self.captureData['captureID']).name + ' ') + mls.UI_INFLIGHT_CAPTURING)
                newTimeText = self.GetCaptureTimeString(portion)
                if (timeText.text != newTimeText):
                    textWidth = uix.GetTextWidth(newTimeText, fontsize=9, hspace=1, uppercase=1)
                    timeText.text = newTimeText
                    timeText.left = -8
                if (portion < 0.0):
                    self.SetCaptureLogo(self.captureData['lastCapturing'])
                else:
                    self.SetCaptureLogo(self.captureData['captureID'])
            else:
                self.SetCaptureLogo(self.captureData['lastCapturing'])
                portion = (float(self.captureData['points']) / 100)
                width = min(int((portion * fillwidth)), fillwidth)
                width = abs(width)
                if (p.width != width):
                    p.width = width
                t.text = mls.UI_INFLIGHT_CONTESTED
                break
            blue.pyos.synchro.Sleep(500)

        if (self and (not self.destroyed)):
            timeText.text = self.GetCaptureTimeString(portion)
        self.captureTaskletRunning = False



    def GetCaptureTimeString(self, portion):
        if (self.captureData['captureID'] == 'contested'):
            return ' '
        else:
            timeScalar = (1 - portion)
            if (timeScalar <= 0):
                return mls.UI_INFLIGHT_CAPTURED
            maxTime = self.captureData['captureTime']
            timeLeft = (timeScalar * maxTime)
            properTime = long(((60000L * const.dgmTauConstant) * timeLeft))
            return util.FmtDate(properTime, 'ns')



    def SetCaptureLogo(self, teamID):
        if (teamID == 'contested'):
            return 
        if self.sr.Get('captureLogo'):
            if (self.sr.captureLogo.name == cfg.eveowners.Get(teamID).name):
                return 
            self.sr.captureLogo.Close()
        raceIDByTeamID = {const.factionCaldariState: const.raceCaldari,
         const.factionMinmatarRepublic: const.raceMinmatar,
         const.factionAmarrEmpire: const.raceAmarr,
         const.factionGallenteFederation: const.raceGallente}
        logo = uicls.LogoIcon(itemID=raceIDByTeamID.get(teamID, teamID), parent=self, state=uiconst.UI_DISABLED, size=32, pos=(-70, 22, 32, 32), name=cfg.eveowners.Get(teamID).name, align=uiconst.RELATIVE, ignoreSize=True)
        self.sr.captureLogo = logo



    def StructureProgress(self, lastPosEvent, stateName, stateTimestamp, stateDelay):
        if self.destroyed:
            return 
        t = self.sr.posStatus
        uicls.Frame(parent=self, align=uiconst.TOPLEFT, width=82, height=13, left=18, top=30, color=(1.0, 1.0, 1.0, 0.5))
        p = uicls.Fill(parent=self, align=uiconst.TOPLEFT, width=80, height=11, left=19, top=31, color=(1.0, 1.0, 1.0, 0.25))
        startTime = blue.os.GetTime()
        if stateDelay:
            stateDelay = float((stateDelay * const.MSEC))
        doneStr = {'anchoring': mls.UI_INFLIGHT_ANCHORED.lower(),
         'onlining': mls.UI_INFLIGHT_ONLINE.lower(),
         'unanchoring': mls.UI_INFLIGHT_UNANCHORED.lower(),
         'reinforced': mls.UI_INFLIGHT_ONLINE.lower(),
         'operating': mls.UI_INFLIGHT_ONLINE.lower(),
         'incapacitated': mls.UI_INFLIGHT_INCAPACITATED.lower()}.get(stateName, mls.UI_GENERIC_DONE)
        endTime = 0
        if stateDelay:
            endTime = (stateTimestamp + stateDelay)
        while (1 and endTime):
            if ((not self) or (self.destroyed or (lastPosEvent != self.lastPosEvent))):
                return 
            timeLeft = (endTime - blue.os.GetTime())
            portion = (timeLeft / stateDelay)
            timeLeftSec = (timeLeft / 1000.0)
            if (timeLeft <= 0):
                t.text = doneStr
                break
            t.text = ((getattr(mls, ('UI_GENERIC_' + stateName.upper())) + '...<br>') + util.FmtDate(long(timeLeft), 'ss'))
            p.width = int((80 * portion))
            blue.pyos.synchro.Yield()

        blue.pyos.synchro.Sleep(250)
        if ((not self) or self.destroyed):
            return 
        for each in self.children[-2:]:
            if ((each is not None) and (not getattr(each, 'destroyed', 0))):
                each.Close()

        if (lastPosEvent != self.lastPosEvent):
            return 
        t.text = ''
        blue.pyos.synchro.Sleep(250)
        if ((not self) or (self.destroyed or (lastPosEvent != self.lastPosEvent))):
            return 
        t.text = doneStr
        blue.pyos.synchro.Sleep(250)
        if ((not self) or (self.destroyed or (lastPosEvent != self.lastPosEvent))):
            return 
        t.text = ''
        blue.pyos.synchro.Sleep(250)
        if ((not self) or (self.destroyed or (lastPosEvent != self.lastPosEvent))):
            return 
        t.text = doneStr



    def OrbitalProgress(self, lastOrbitalEvent, slimItem):
        if self.destroyed:
            return 
        t = self.sr.orbitalStatus
        uicls.Frame(parent=self, align=uiconst.TOPLEFT, width=82, height=13, left=18, top=30, color=(1.0, 1.0, 1.0, 0.5))
        p = uicls.Fill(parent=self, align=uiconst.TOPLEFT, width=80, height=11, left=19, top=31, color=(1.0, 1.0, 1.0, 0.25))
        startTime = blue.os.GetTime()
        stateName = entities.GetEntityStateString(slimItem.orbitalState)
        stateTimestamp = slimItem.orbitalTimestamp
        stateDelay = None
        doneText = mls.UI_GENERIC_DONE
        godmaSM = sm.GetService('godma').GetStateManager()
        if (slimItem.orbitalState == entities.STATE_ANCHORING):
            stateDelay = godmaSM.GetType(slimItem.typeID).anchoringDelay
            doneText = entities.GetEntityStateString(entities.STATE_ANCHORED)
        elif (slimItem.orbitalState == entities.STATE_ONLINING):
            stateDelay = godmaSM.GetType(slimItem.typeID).onliningDelay
            doneText = mls.UI_GENERIC_ONLINE
        elif (slimItem.orbitalState == entities.STATE_UNANCHORING):
            stateDelay = godmaSM.GetType(slimItem.typeID).unanchoringDelay
            doneText = entities.GetEntityStateString(entities.STATE_UNANCHORED)
        endTime = 0
        if stateDelay:
            stateDelay = float((stateDelay * const.MSEC))
            endTime = (stateTimestamp + stateDelay)
        while endTime:
            if ((not self) or (self.destroyed or (lastOrbitalEvent != self.lastOrbitalEvent))):
                return 
            timeLeft = (endTime - blue.os.GetTime())
            portion = (timeLeft / stateDelay)
            if (timeLeft <= 0):
                t.text = doneText
                break
            t.text = ((stateName + '...<br>') + util.FmtTimeInterval(long(timeLeft), breakAt='sec'))
            p.width = int((80 * portion))
            blue.pyos.synchro.Yield()

        blue.pyos.synchro.Sleep(250)
        if ((not self) or self.destroyed):
            return 
        for each in self.children[-2:]:
            if ((each is not None) and (not getattr(each, 'destroyed', 0))):
                each.Close()

        if (lastOrbitalEvent != self.lastOrbitalEvent):
            return 
        t.text = ''
        blue.pyos.synchro.Sleep(250)
        if ((not self) or (self.destroyed or (lastOrbitalEvent != self.lastOrbitalEvent))):
            return 
        t.text = doneText
        blue.pyos.synchro.Sleep(250)
        if ((not self) or (self.destroyed or (lastOrbitalEvent != self.lastOrbitalEvent))):
            return 
        t.text = ''
        blue.pyos.synchro.Sleep(250)
        if ((not self) or (self.destroyed or (lastOrbitalEvent != self.lastOrbitalEvent))):
            return 
        t.text = doneText



    def SetBracketAnchoredState(self, slimItem):
        if not cfg.invgroups.Get(slimItem.groupID).anchorable:
            return 
        if ((not slimItem) or ((slimItem.itemID == eve.session.shipid) or ((slimItem.ownerID != eve.session.charid) and (slimItem.ownerID != eve.session.corpid)))):
            return 
        ball = self.trackBall
        if (ball is None):
            bp = sm.GetService('michelle').GetBallpark()
            ball = bp.GetBall(slimItem.itemID)
            if not ball:
                return 
        (_iconX, _iconY, _dockType, _minDist, _maxDist, _iconOffset, _logflag,) = sm.GetService('bracket').GetBracketProps(slimItem, ball)
        (iconX, iconY, dockType, minDist, maxDist, iconOffset, logflag,) = self.data
        for each in self.children:
            if (each.name == 'anchoredicon'):
                if ball.isFree:
                    self.data = (iconX,
                     iconY,
                     dockType,
                     _minDist,
                     _maxDist,
                     iconOffset,
                     logflag)
                    each.Close()
                return 

        if not ball.isFree:
            self.data = (iconX,
             iconY,
             dockType,
             0.0,
             1e+32,
             iconOffset,
             logflag)
            anchor = uicls.Icon(icon='ui_38_16_15', parent=self, pos=(0, 16, 16, 16), align=uiconst.TOPLEFT)
            anchor.name = 'anchoredicon'




class BaseBracket(SlimDeco):
    __guid__ = 'xtriui.BaseBracket'

    def init(self):
        self.LoadEvents(['Close'])
        self.IsBracket = 1
        self.Reset()



    def Reset(self):
        self.displayName = ''
        self.sr.icon = None
        self.sr.tempIcon = None
        self.sr.label = None
        self.sr.hitchhiker = None
        self.sr.flag = None
        self.sr.bgColor = None
        self.sr.hostile_attacking = None
        self.sr.hilite = None
        self.sr.selection = None
        self.sr.posStatus = None
        self.sr.orbitalStatus = None
        self.trackBall = None
        self.trackTransform = None
        self.sr.trackBall = None
        self.sr.trackTransform = None
        self.fadeColor = True
        self.iconX = None
        self.iconY = None
        self.iconXOffset = 0
        self.lastPosEvent = None
        self.lastOrbitalEvent = None
        self.scanAttributeChangeFlag = False
        self.iconTop = 0



    def OnStateChange(self, itemID, flag, true, *args):
        if ((flag == state.lookingAt) and hasattr(self, 'ShowTempIcon')):
            if self.stateItemID == eve.session.shipid == itemID:
                if not true:
                    self.ShowTempIcon()
                else:
                    self.HideTempIcon()
        if (self.stateItemID != itemID):
            return 
        if (flag == state.mouseOver):
            self.Hilite(true)
        elif (flag == state.selected):
            self.Select(true)



    def Startup(self, itemID, groupID, categoryID, iconX, iconY):
        self.iconX = iconX
        self.iconY = iconY
        self.LoadIcon(iconX, iconY)
        self.itemID = self.stateItemID = itemID
        self.groupID = groupID
        self.categoryID = categoryID



    def LoadIcon(self, iconX, iconY):
        if (getattr(self, 'noIcon', 0) == 1):
            return 
        if not self.sr.icon:
            icon = BracketChild(blue.os.LoadObject('res:/UI/Inflight/bracketicon.blue'))
            icon.Startup(self)
            icon.name = 'mainicon'
            icon.left = 0
            icon.top = (self.iconXOffset or self.iconTop)
            icon.state = uix.UI_NORMAL
            icon.rectWidth = icon.rectHeight = 16
            self.children.append(icon)
            if self.fadeColor:
                self.color = icon.color
            else:
                icon.color.a = 0.75
            self.sr.icon = icon
        self.sr.icon.rectLeft = int((iconX * 256))
        self.sr.icon.rectTop = int((iconY * 256))



    def LoadNoneIcon(self):
        fill = BracketChild(uicls.Fill(parent=self, color=(0.0, 0.0, 0.0, 0.0), state=uiconst.UI_NORMAL))
        fill.name = 'mainicon'
        fill.Startup(self)



    def ShowTempIcon(self):
        if (getattr(self, 'noIcon', 0) == 1):
            return 
        if not self.sr.tempIcon:
            tempicon = BracketChild(blue.os.LoadObject('res:/UI/Inflight/bracketicon.blue'))
            tempicon.Startup(self)
            tempicon.name = 'tempicon'
            tempicon.rectLeft = int((self.iconX * 256))
            tempicon.rectTop = int((self.iconY * 256))
            tempicon.rectWidth = tempicon.rectHeight = 16
            if self.sr.icon:
                tempicon.top = self.sr.icon.top
                tempicon.left = self.sr.icon.left
                tempicon.autoPos = self.sr.icon.autoPos
            else:
                tempicon.top = 0
                tempicon.left = 0
                tempicon.autoPos = uix.AUTOPOSXCENTER
            tempicon.state = uix.UI_NORMAL
            tempicon.color.a = 0.75
            try:
                self.children.insert(0, tempicon)
            except:
                print 'FAILED',
                print self.__guid__
            self.sr.tempIcon = tempicon
        if self.sr.icon:
            self.sr.tempIcon.color.SetRGB(self.sr.icon.color.r, self.sr.icon.color.g, self.sr.icon.color.b, self.sr.icon.color.a)
            self.sr.icon.state = uix.UI_HIDDEN
        self.sr.tempIcon.state = uix.UI_NORMAL



    def HideTempIcon(self):
        lookingAt = sm.GetService('state').GetExclState(state.lookingAt)
        if ((self.stateItemID == eve.session.shipid) and (lookingAt != eve.session.shipid)):
            return 
        if self.sr.tempIcon:
            t = self.sr.tempIcon
            self.sr.tempIcon = None
            t.Close()
        if self.sr.icon:
            self.sr.icon.state = uix.UI_NORMAL



    def ShowLabel(self, *args):
        if ((not self.destroyed) and ((self.displayName == '') or (not getattr(self, 'showLabel', True)))):
            return 
        if not ((self.itemID == eve.session.shipid) and self.sr.Get('tempIcon', None)):
            return 
        if not self.sr.label:
            self.sr.label = BracketLabel(uicls.Container(parent=self.parent, name='labelparent', idx=0, align=uiconst.ABSOLUTE, width=512, height=16, state=uiconst.UI_NORMAL))
            self.sr.label.Startup(self)
        if (getattr(self, 'showLabel', True) == SHOWLABELS_ONMOUSEENTER):
            self.ShowTempIcon()



    def KillLabel(self):
        if not sm.GetService('bracket').ShowingHidden():
            self.HideTempIcon()
        if (getattr(self, 'showLabel', True) == SHOWLABELS_ONMOUSEENTER):
            l = self.sr.label
            self.sr.label = None
            if l:
                l.Close()



    def Select(self, true):
        if true:
            if not self.sr.selection:
                self.sr.selection = blue.os.LoadObject('res:/UI/Inflight/bracketselection.blue')
                self.sr.selection.width = self.sr.selection.height = 18
                self.sr.selection.left = self.sr.selection.top = 0
                self.sr.selection.autoPos = uix.AUTOPOSCENTER
                self.children.append(self.sr.selection)
            self.sr.selection.state = uix.UI_DISABLED
            self.ShowLabel()
        elif self.sr.selection:
            self.sr.selection.state = uix.UI_HIDDEN
        self.KillLabel()



    def Hilite(self, true):
        if (true and (self.state != uix.UI_HIDDEN)):
            uthread.pool('Bracket::Hilite', self._ShowLabel)
        elif ((self.trackBall or self.trackTransform) and (sm.GetService('state').GetExclState(state.selected) != self.itemID)):
            self.KillLabel()



    def _ShowLabel(self):
        blue.pyos.synchro.Sleep(50)
        over = eve.triapp.uilib.mouseOver
        if self.destroyed:
            return 
        if ((getattr(over, 'stateItemID', None) == self.itemID) or (getattr(over, '__guid__', '').startswith('xtriui.BracketChild') and (over.wr.bracket and (over.wr.bracket == self)))):
            self.ShowLabel()



    def GetDistance(self):
        if (self.trackBall or self.sr.trackBall):
            b = (self.trackBall or self.sr.trackBall)
            return b.surfaceDist
        if getattr(self.wr, 'slimItem', None):
            slimItem = self.wr.slimItem
            ballPark = sm.GetService('michelle').GetBallpark()
            if (ballPark and (slimItem.itemID in ballPark.balls)):
                return ballPark.balls[slimItem.itemID].surfaceDist
        elif (self.trackTransform or self.sr.trackTransform):
            tf = (self.trackTransform or self.sr.trackTransform)
            trans = tf.translation
            pos = trinity.TriVector(trans[0], trans[1], trans[2])
            import maputils
            myPos = maputils.GetMyPos()
            return (pos - myPos).Length()



    def HideBubble(self):
        if (self.sr.Get('bubble', None) is not None):
            self.sr.bubble.Close()
            self.sr.bubble = None



    def ShowBubble(self, hint):
        if (self.sr.Get('bubble', None) is not None):
            self.sr.bubble.Close()
            self.sr.bubble = None
        if hint:
            bubble = xtriui.BubbleHint(uicls.Container(parent=self, name='bubblehint', align=uiconst.TOPLEFT, width=0, height=0, idx=0, state=uiconst.UI_PICKCHILDREN))
            pointer = {const.groupStargate: 5,
             const.groupStation: 3}.get(self.groupID, 0)
            bubble.ShowHint(hint, pointer)
            self.sr.bubble = bubble
            self.sr.bubble.state = uix.UI_NORMAL




class Bracket(BaseBracket, UpdateEntry):
    __guid__ = 'xtriui.Bracket'
    broadcastIconSize = ('bigIcon', 32)

    def Startup(self, slimItem, ball = None, transform = None):
        (self.iconX, self.iconY, dockType, minDist, maxDist, iconOffset, logflag,) = self.data
        self.wr.slimItem = slimItem
        self.itemID = slimItem.itemID
        self.groupID = slimItem.groupID
        self.categoryID = slimItem.categoryID
        xtriui.UpdateEntry.Startup_update(self)
        self.hostilePath = 'res:/UI/Inflight/minibracket_hostile.blue'
        self.targetedPath = 'res:/UI/Inflight/minibracket_targeted.blue'
        self.activetargetPath = 'res:/UI/Inflight/minibracket_active.blue'
        if not self.invisible:
            self.LoadIcon(self.iconX, self.iconY)
        else:
            self.LoadNoneIcon()
        self.UpdateStructureState(slimItem)
        self.UpdateOrbitalState(slimItem)
        self.UpdateCaptureProgress(None)
        self.UpdateOutpostState(slimItem)
        self.UpdatePlanetaryLaunchContainer(slimItem)
        self.SetBracketAnchoredState(slimItem)
        xtriui.UpdateEntry.Load_update(self, slimItem)



    def OnStateChange(self, *args):
        xtriui.UpdateEntry.OnStateChange(self, *args)



    def GetMenu(self):
        return sm.GetService('menu').CelestialMenu(self.itemID, slimItem=self.wr.slimItem)



    def OnAttribute(self, attributeName, item, newValue):
        self.scanAttributeChangeFlag = True



    def CountDown(self, target):
        if self.destroyed:
            return 
        self.scanAttributeChangeFlag = False
        slimItem = self.wr.slimItem
        source = eve.session.shipid
        time = sm.GetService('bracket').GetScanSpeed(source, slimItem)
        if target:
            par = uicls.Container(parent=target, width=82, height=13, left=36, top=37, align=uiconst.TOPLEFT, state=uix.UI_DISABLED)
            t = uicls.Label(text='', parent=par, width=200, autowidth=False, left=6, top=1, fontsize=9, letterspace=1, uppercase=1, state=uiconst.UI_NORMAL)
            p = uicls.Fill(parent=par, align=uiconst.TOPLEFT, width=80, height=11, left=1, top=1, color=(1.0, 1.0, 1.0, 0.25))
            uicls.Frame(parent=par, color=(1.0, 1.0, 1.0, 0.5))
            startTime = blue.os.GetTime()
            while 1:
                now = blue.os.GetTime()
                dt = blue.os.TimeDiffInMs(startTime, now)
                if self.scanAttributeChangeFlag:
                    waitRatio = (dt / float(time))
                    self.scanAttributeChangeFlag = False
                    time = sm.GetService('bracket').GetScanSpeed(source, slimItem)
                    startTime = (now - long(((time * waitRatio) * 10000)))
                    dt = blue.os.TimeDiffInMs(startTime, now)
                if t.destroyed:
                    return 
                t.text = ('%.3f %s' % (((time - dt) / 1000.0), [mls.UI_GENERIC_SECONDSHORT, mls.UI_GENERIC_SECONDSSHORT][(((time - dt) / 1000.0) > 2.0)]))
                if (dt > time):
                    t.text = mls.UI_INFLIGHT_LOCKED
                    break
                p.width = int((80 * ((time - dt) / time)))
                blue.pyos.synchro.Yield()

            blue.pyos.synchro.Sleep(250)
            if t.destroyed:
                return 
            t.text = ''
            blue.pyos.synchro.Sleep(250)
            if t.destroyed:
                return 
            t.text = mls.UI_INFLIGHT_LOCKED
            blue.pyos.synchro.Sleep(250)
            if t.destroyed:
                return 
            t.text = ''
            blue.pyos.synchro.Sleep(250)
            if t.destroyed:
                return 
            t.text = mls.UI_INFLIGHT_LOCKED
            blue.pyos.synchro.Sleep(250)
            par.Close()



    def GBEnemySpotted(self, active, fleetBroadcastID, charID):
        self.NearIDFleetBroadcast(active, fleetBroadcastID, charID, 'EnemySpotted')



    def GBNeedBackup(self, active, fleetBroadcastID, charID):
        self.NearIDFleetBroadcast(active, fleetBroadcastID, charID, 'NeedBackup')



    def GBInPosition(self, active, fleetBroadcastID, charID):
        self.NearIDFleetBroadcast(active, fleetBroadcastID, charID, 'InPosition')



    def GBHoldPosition(self, active, fleetBroadcastID, charID):
        self.NearIDFleetBroadcast(active, fleetBroadcastID, charID, 'HoldPosition')



    def NearIDFleetBroadcast(self, active, fleetBroadcastID, charID, broadcastType):
        inBubble = bool(util.SlimItemFromCharID(charID))
        if inBubble:
            return self.FleetBroadcast(active, broadcastType, fleetBroadcastID, charID)
        if active:
            self.fleetBroadcastSender = charID
            self.fleetBroadcastType = broadcastType
            self.fleetBroadcastID = fleetBroadcastID
            if (self.sr.Get('fleetBroadcastIcon') and (self.sr.fleetBroadcastIcon is not None)):
                self.sr.fleetBroadcastIcon.Close()
                self.sr.fleetBroadcastIcon = None
            icon = fleetbr.types[broadcastType]['bigIcon']
            (sizeName, pixels,) = self.broadcastIconSize
            icon = fleetbr.types[broadcastType][sizeName]
            iconLeft = (((self.sr.icon.width / 2) + self.sr.icon.left) - (pixels / 2))
            iconTop = (((self.sr.icon.height / 2) + self.sr.icon.top) - (pixels / 2))
            self.sr.fleetBroadcastIcon = uicls.Icon(icon='ui_44_16_53', parent=self, align=uiconst.RELATIVE, pos=(0, 0, 16, 16), state=uiconst.UI_DISABLED)
            self.sr.fleetBroadcastIcon.name = 'fleetBroadcastIcon'
            self.sr.fleetBroadcastIcon.state = uix.UI_NORMAL
        elif (fleetBroadcastID == getattr(self, 'fleetBroadcastID', None)):
            if (self.sr.Get('fleetBroadcastIcon') and (self.sr.fleetBroadcastIcon is not None)):
                self.sr.fleetBroadcastIcon.Close()
                self.sr.fleetBroadcastIcon = None
            self.fleetBroadcastSender = self.fleetBroadcastType = self.fleetBroadcastID = None




def _FixLines(target):

    def FindLine(name):
        return uiutil.FindChild(target, 'lines', name)


    (l, r, t, b,) = map(FindLine, ['lineleft',
     'lineright',
     'linetop',
     'linebottom'])
    l.left -= (eve.triapp.uilib.desktop.width - l.width)
    l.width = r.width = eve.triapp.uilib.desktop.width
    t.top -= (eve.triapp.uilib.desktop.height - t.height)
    t.height = b.height = eve.triapp.uilib.desktop.height



def IsAbandonedContainer(slimItem):
    bp = sm.StartService('michelle').GetBallpark()
    if (bp is None):
        return False
    else:
        if bp.IsAbandoned(slimItem.itemID):
            return True
        return False



def IsForbiddenContainer(slimItem):
    if (slimItem.groupID not in (const.groupWreck,
     const.groupCargoContainer,
     const.groupSecureCargoContainer)):
        return False
    else:
        if not slimItem.ownerID:
            return False
        if (slimItem.ownerID == eve.session.charid):
            return False
        if (slimItem.corpID and (slimItem.corpID == eve.session.corpid)):
            return False
        if (slimItem.allianceID and (slimItem.allianceID == eve.session.allianceid)):
            return False
        if sm.GetService('corp').GetMember(slimItem.ownerID):
            return False
        if sm.GetService('fleet').IsMember(slimItem.ownerID):
            return False
        bp = sm.StartService('michelle').GetBallpark()
        if (bp is None):
            return False
        if bp.HaveLootRight(slimItem.itemID):
            return False
        return True


exports = util.AutoExports('bracket', locals())

